package com.techysky.controller;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.techysky.repository.CustomRepository;
import com.techysky.util.DbOperate;

@Controller
public class DataBackUpController implements Serializable{
	
  /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	String hostIp="127.0.0.1";
	@Value("${spring.datasource.username}")
	private String root;
	@Value("${spring.datasource.password}")
	private String pwd;
	String dbName="hhmse";
	@Autowired
	CustomRepository cr;
	

	/**
	 * 备份
	 * @param path
	 * @return
	 */
	@RequestMapping("/backUp")
	@ResponseBody
	public String backUp(String path) 
	{
		
		String backName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())+".sql";
        try {
			DbOperate.backup(hostIp,root,pwd,path,backName,dbName);
			return "success";
		} catch (Exception e) {
			return "fail";
		}
		
	}
	
	/**
	 * 恢复数据
	 * @param path
	 * @return
	 */
	@RequestMapping("/restore")
	@ResponseBody
	public String restore(String path) 
	{
        try {
			DbOperate.dbRestore(root,pwd,dbName,path);
			return "success";
		} catch (Exception e) {
			return "fail";
		}
	}

	/**
	 * 清除数据
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/dbClean")
	@ResponseBody
	public String  dbClean() throws Exception
	{
		String sql = "select CONCAT('TRUNCATE TABLE "+dbName+".',table_name,';') from information_schema.tables where TABLE_SCHEMA = '"+dbName+"'";
	    List<?> list = cr.getDbList(sql);
	    if(list.size()>0)
	    {
	    	String st = "SET foreign_key_checks=0; ";
	    	String sp = "SET foreign_key_checks=1; ";
	    	cr.cleanDb(st);
	    	for(int i=0;i<list.size();i++)
	    	{
	    		 cr.cleanDb(list.get(i).toString());
	    	}
	    	cr.cleanDb(sp);
	    }
	    return "success";
	}
	
}
